<template>
  <div class="box-border w-full h-full p-10">
    <div class="w-full h-[40px]">
      <div class="flex items-center gap-20">
        <el-button
          type="primary"
          size="large"
          plain
          :loading="isOptimizing"
          :disabled="isOptimizing"
          @click="startOptimization"
        >
          {{ isOptimizing ? '优化中...' : '开始优化' }}
        </el-button>
        <el-progress
          :text-inside="true"
          :stroke-width="20"
          :percentage="progressPercentage"
          :status="progressStatus"
        />
        <div class="flex items-center gap-2">
          <span class="text-gray-600">数据输出时间间隔:</span>
          <el-input v-model="outputInterval" style="width: 100px" placeholder="10" />
          <span class="text-gray-600">min</span>
        </div>
      </div>
    </div>
    <div class="mt-10 w-full h-[calc(100%-100px)] rounded-md border1">
      <div class="w-full h-[54px] flex">
        <div
          v-for="item in options"
          :key="item.id"
          :class="{ '!bg-white shadow1': active === item.id }"
          class="h-full w-[254px] bg-[#F2F2F2] rounded-md flex items-center justify-center cursor-pointer"
          @click="changeActive(item.id)"
        >
          {{ item.label }}
        </div>
      </div>
      <div class="w-full h-[calc(100%-54px)] relative">
        <!-- 加载动画 -->
        <div
          v-if="isLoading"
          class="absolute inset-0 z-10 flex items-center justify-center bg-white bg-opacity-80"
        >
          <div class="text-center">
            <el-icon class="mb-4 text-4xl text-blue-500 is-loading">
              <Loading />
            </el-icon>
            <p class="text-gray-600">能耗优化计算中...</p>
          </div>
        </div>

        <!-- 子组件内容 -->
        <SchemeDiagram
          :ganttData="optimizedGanttData"
          v-if="active === 1 && !isLoading"
        ></SchemeDiagram>
        <SchemeTable
          :ganttData="optimizedGanttData"
          :tableData="optimizedTableData"
          :timeInterval="outputInterval"
          v-if="active === 2 && !isLoading"
        ></SchemeTable>
        <AllLineDiagram
          :simulationTime="simulationTime"
          :timeInterval="outputInterval"
          :chartData1="optimizedChartData1"
          :chartData2="optimizedChartData2"
          v-if="active === 3 && !isLoading"
        ></AllLineDiagram>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import SchemeDiagram from './schemeDiagram.vue'
import SchemeTable from './schemeTable.vue'
import AllLineDiagram from './allLIneDiagram/index.vue'
import { ganttData, tableData, chartData1, chartData2 } from './data'
import { getNengHaoData } from '@/api/nenghao'
import { useSimulationStore } from '@/stores/modules/simulation'
const simulationStore = useSimulationStore()
// 基础状态
const active = ref(1)
const outputInterval = ref('10') // 默认10分钟

// 优化相关状态
const isOptimizing = ref(false)
const progressPercentage = ref(0)
const isLoading = ref(false)

// 优化后的数据
const optimizedGanttData = ref(null)
const optimizedTableData = ref(null)
const optimizedChartData1 = ref(null)
const optimizedChartData2 = ref(null)
const simulationTime = computed(() => simulationStore.simulationTime)
const sps_id = computed(() => simulationStore.sps_id)
const T_g_WBX = computed(() => simulationStore.T_g_WBX)
const T_g_BKX = computed(() => simulationStore.T_g_BKX)
const T_g_701_ZZ = computed(() => simulationStore.T_g_701_ZZ)
const T_g_81_701 = computed(() => simulationStore.T_g_81_701)
const Oil_in0 = computed(() => simulationStore.Oil_in0)
const Oil_in1 = computed(() => simulationStore.Oil_in1)
const Oil_in2 = computed(() => simulationStore.Oil_in2)
const QS_time = computed(() => simulationStore.QS_time)
const TS_time = computed(() => simulationStore.TS_time)

// 进度条状态
const progressStatus = computed(() => {
  if (progressPercentage.value === 0) return ''
  if (progressPercentage.value === 100) return 'success'
  return ''
})

// 选项配置
const options = ref([
  {
    id: 1,
    label: '运行方案图'
  },
  {
    id: 2,
    label: '运行方案报表'
  },
  {
    id: 3,
    label: '全线参数变化图'
  }
])

// 切换激活状态
const changeActive = (id) => {
  active.value = id
}

// 开始优化
const startOptimization = async () => {
  if (isOptimizing.value) return

  isOptimizing.value = true
  progressPercentage.value = 0
  isLoading.value = true

  // 清空之前的数据
  optimizedGanttData.value = null
  optimizedTableData.value = null
  optimizedChartData1.value = null
  optimizedChartData2.value = null

  // 清理之前的进度条定时器
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }
  if (progressResolve) {
    progressResolve = null
  }

  try {
    // 开始获取数据，同时显示进度条
    await loadOptimizedData()

    ElMessage.success('优化完成！')
  } catch (error) {
    ElMessage.error('优化失败，请重试')
    console.error('优化失败:', error)
  } finally {
    isOptimizing.value = false
    isLoading.value = false
  }
}

// 加载优化后的数据
const loadOptimizedData = async () => {
  // 开始进度条动画
  const progressPromise = simulateProgress()

  // 同时调用接口获取数据
  const dataPromise = getNengHaoData({
    sps_id: sps_id.value,
    TS_time: TS_time.value,
    QS_time: QS_time.value,
    Time_end: parseInt(simulationTime.value),
    T_g_WBX: T_g_WBX.value,
    T_g_BKX: T_g_BKX.value,
    T_g_701_ZZ: T_g_701_ZZ.value,
    T_g_81_701: T_g_81_701.value,
    Oil_in0: Oil_in0.value,
    Oil_in1: Oil_in1.value,
    Oil_in2: Oil_in2.value,
    interval_min: outputInterval.value || '10'
  })

  // 等待数据获取完成
  const response = await dataPromise

  // 处理获取到的数据
  if (response && response.data && response.data.length > 0) {
    const data = response.data[0]

    // 数据映射
    simulationStore.simulationTime = Math.round(data.max_time_info / 60) // 转换为分钟
    optimizedChartData1.value = data.distance_variation_data
    optimizedChartData2.value = data.distance_variation_branch_data
    optimizedTableData.value = data.time_variation_data
    optimizedGanttData.value = data.pump_status
  } else {
    // 如果没有数据，使用默认数据
    optimizedGanttData.value = ganttData
    optimizedTableData.value = tableData
    optimizedChartData1.value = chartData1
    optimizedChartData2.value = chartData2
  }

  // 接口完成后，调整进度条
  adjustProgressAfterCompletion()

  // 等待进度条完成
  await progressPromise
}

// 进度条控制变量
let progressTimer = null
let progressResolve = null

// 动态进度条动画
const simulateProgress = () => {
  return new Promise((resolve) => {
    progressResolve = resolve
    const interval = 100 // 每100ms更新一次
    let currentProgress = 0

    progressTimer = setInterval(() => {
      // 缓慢增长进度条，最多到85%
      currentProgress += Math.random() * 0.1 + 0.02 // 每次增长0.2-0.7%
      if (currentProgress > 95) {
        currentProgress = 95
      }
      progressPercentage.value = Math.round(currentProgress)
    }, interval)
  })
}

// 接口完成后调整进度条
const adjustProgressAfterCompletion = () => {
  if (progressTimer) {
    clearInterval(progressTimer)
    progressTimer = null
  }

  // 完成到100%
  const completeProgress = () => {
    if (progressPercentage.value < 100) {
      // 每次增加2%，让进度条平稳完成
      progressPercentage.value += 2
      setTimeout(completeProgress, 100) // 100ms间隔，平稳完成
    } else {
      progressPercentage.value = 100
      if (progressResolve) {
        progressResolve()
        progressResolve = null
      }
    }
  }

  completeProgress()
}
</script>

<style lang="scss" scoped>
:deep(.el-progress--line) {
  width: 400px;
}

.border1 {
  border: 1px solid #457ab2;
}
.shadow1 {
  box-shadow: 4px 4px 14px 0px rgba(0, 0, 0, 0.25);
}
</style>
